package com.shop.servlet.impl;

import com.shop.dao.ShopDao;
import com.shop.dao.impl.ShopCatDaoImpl;
import com.shop.entity.Goods;
import com.shop.entity.ShopCat;
import com.shop.servlet.ShopCatServlet;

import java.sql.SQLException;

/**
 * com.shop.servlet.impl文档说明
 *
 * @author Angluzha
 * @version 2022/9/21
 */
public class ShopCatServletImpl extends BaseServletImpl<ShopCat> implements ShopCatServlet {
    {
        dao = new ShopCatDaoImpl();
    }

    @Override
    public boolean save(ShopCat shopCat) {
        try {
            GoodsServletImpl servlet = new GoodsServletImpl();
            Goods goods = servlet.selectOne(new Goods(shopCat.getPid()));

            ShopDao dao = (ShopDao) this.dao;
            ShopCat cat = dao.exist(shopCat);
            if (cat!=null){
                cat.setQuantity(cat.getQuantity()+shopCat.getQuantity());
                shopCat = cat;
                shopCat.setQuantity(goods.getStock()>=shopCat.getQuantity()?shopCat.getQuantity():goods.getStock());
                dao.addQuantity(shopCat);
            }else{
                shopCat.setQuantity(goods.getStock()>=shopCat.getQuantity()?shopCat.getQuantity():goods.getStock());
                dao.insert(shopCat);
            }
        } catch (Exception e) {
            return false;
        }

        return true;
    }

    @Override
    public Integer getCountByUid(Integer id) {
        try {
            ShopDao dao = (ShopDao) this.dao;
            return dao.selectCountByUid(id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean revise(Integer id, Integer status) {
        try {
            GoodsServletImpl servlet = new GoodsServletImpl();
            ShopCat shopCat= (ShopCat) this.dao.selectOne(new ShopCat(id));

            Goods goods = servlet.selectOne(new Goods(shopCat.getPid()));
            int quantity = shopCat.getQuantity() + status;
            if (goods.getStock()>=quantity&&quantity>0){
                ShopDao dao = (ShopDao) this.dao;
                return dao.revise(id,status);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return false;
    }
}
